"use server";

import { revalidatePath } from "next/cache";
import { Post, User } from "./models";
import { signIn, signOut } from "./auth";
import { createUser } from "./data";
import bcrypt from "bcrypt";

export const sayHello = async (formData) => {
  const { title, body, img, userId } = Object.fromEntries(formData);
  const post = new Post({ title, body, img, userId });
  await post.save();
  // 不是页面的跳转，而是重新生成页面，更新原有的页面，不会有闪烁。服务端数据，正常点击过去不会再请求了
  revalidatePath("/blog");
};

export const deleteById = async (formData) => {
  const { id } = Object.fromEntries(formData);
  await Post.findByIdAndDelete(id);
  revalidatePath("/blog");
};

export const onGithubLogin = async () => {
  await signIn("github");
};

export const onLogout = async () => {
  await signOut({ redirectTo: "/login" });
};

export const register = async (previousState, formData) => {
  const { username, email, password, passwordRepeat } =
    Object.fromEntries(formData);
  if (password !== passwordRepeat) {
    return { reason: "passwords are not the same" };
  }

  const user = await User.findOne({ username });
  if (!user) {
    const salt = await bcrypt.genSalt(10);
    const hashPassword = await bcrypt.hash(password, salt);
    await createUser({
      email,
      username,
      password: hashPassword,
    });
    return { code: 0 };
  } else {
    return { reason: "user already exists" };
  }
};

export const login = async (prev, formData) => {
  const { username, password } = Object.fromEntries(formData);

  try {
    const res = await signIn("credentials", { username, password });
  } catch (error) {
    // error?.cause?.err?.message 获取登录失败的原因
    if (error?.cause?.err?.message) {
      return { reason: error?.cause?.err?.message };
    }
    // NEXT_REDIRECT error use this
    throw error;
  }
};
